/* -----------------
* brief
* 1. this is code gen by tools
* 2. for add/update/delete/query the data save in sql database
 */

package adminSaas

import (
	"github.com/mjiulee/lego"
	"saas_sys_base/common"

	//"github.com/mjiulee/lego/utils"
)


/* 根据id获取记录
 * -----------------
 */
func (t *AdminSaasMenu) ListTopMenu(who *common.Who) []AdminSaasMenu {
	list := make([]AdminSaasMenu, 0)
	lego.GetDBEngine().Where("m_type = ?", 1).And("mini_app_id = ?", who.MiniAppId).Asc("sort_idx").Find(&list)
	return list
}

func (t *AdminSaasMenu) ListTopMenuAndMenuMode(who *common.Who, menuMode int) []AdminSaasMenu {
	list := make([]AdminSaasMenu, 0)
	lego.GetDBEngine().Where("m_type = ?", 1).And("mini_app_id = ?", who.MiniAppId).
		And("menu_mode = ?", menuMode).Asc("sort_idx").Find(&list)
	return list
}

func (t *AdminSaasMenu) ListSubMenuById(who *common.Who, pid int64) []AdminSaasMenu {
	list := make([]AdminSaasMenu, 0)
	lego.GetDBEngine().Where("pid = ?", pid).And("mini_app_id = ?", who.MiniAppId).Asc("sort_idx").Find(&list)
	return list
}


/* 根据id获取记录
 * -----------------
 */
func (t *AdminSaasMenu) RecodeById(id int64) *AdminSaasMenu {
	item := new(AdminSaasMenu)
	_, err := lego.GetDBEngine().ID(id).Get(item)
	if err != nil || item.Id <= 0 {
		return nil
	}
	return item
}

func (t *AdminSaasMenu) RecodeByIdAndMenuMode(id int64, menuMode int) *AdminSaasMenu {
	item := new(AdminSaasMenu)
	item.MenuMode = menuMode
	_, err := lego.GetDBEngine().ID(id).Get(item)
	if err != nil || item.Id <= 0 {
		return nil
	}
	return item
}

/* 根据菜单名称获取记录
 * -----------------
 */
func (t *AdminSaasMenu) RecodeByName(name string) *AdminSaasMenu {
	item := new(AdminSaasMenu)
	item.Name = name
	lego.GetDBEngine().Get(item)
	if item.Id <= 0 {
		return nil
	}
	return item
}

func (t *AdminSaasMenu) ListByNameAndMenuMode(appwho *common.Who, name string, menuMode int ) []AdminSaasMenu {
	resultList := make([]AdminSaasMenu, 0)
	common.GetDBEngineWithFilterByAppId(appwho).And("name = ?", name).And("menu_mode = ?", menuMode).Find(&resultList)

	return resultList
}

/* 添加
 * -----------------
 */
func (t *AdminSaasMenu) AddRecode(item2add *AdminSaasMenu) bool {
	item2add.Id = lego.UUID()
	_, err := lego.GetDBEngine().Insert(item2add)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

/* 删除(硬删除)*/
func (t *AdminSaasMenu) DelRecodeById(id int64) bool {
	item := new(AdminSaasMenu)
	_, err := lego.GetDBEngine().ID(id).Delete(item)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

/* 更新
 * -----------------*/
func (t *AdminSaasMenu) UpdateRecode(rc *AdminSaasMenu) bool {
	_, err := lego.GetDBEngine().Id(rc.Id).Omit("id", "if_del").MustCols("url").Update(rc)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}
